package net.vsame.url2sql.web;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import net.vsame.url2sql.domain.InterceptorConfig;
import net.vsame.url2sql.domain.Url2SqlContext;
import net.vsame.url2sql.domain.Url2SqlModel;
import net.vsame.url2sql.domain.Url2SqlModelChain;
import net.vsame.url2sql.domain.UrlConfig;
import net.vsame.url2sql.helper.JsHelper;
import net.vsame.url2sql.helper.Url2SqlMappingHelper;
import net.vsame.url2sql.helper.WebHelper;

public class Url2SqlCore extends Url2SqlModel{

	/**
	 * 执行Java代码
	 * @param class1
	 * @param method2
	 */
	private static void invoke(Class<?> clazz, Method method){
		try {
			Object o = clazz.newInstance();
			method.invoke(o);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e.getTargetException());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public boolean isWeb() {
		return false;
	}

	@Override
	public void init() {
	}

	@Override
	public void invoke(Url2SqlModelChain chain) {
		Url2SqlContext context = WebHelper.getContext();
		UrlConfig urlConfig = context.getUrlConfig();
		String url = context.getRequestUrl();
		
		//执行拦截器
		List<InterceptorConfig> interceptors = Url2SqlMappingHelper.getInterceptorConfigs();
		for(InterceptorConfig c : interceptors){
			if(c.getRegex()!=null && url.matches(c.getRegex())){
				JsHelper.execute(c.getJs());
				if(context.hasError()){
					//拦截
					return ;
				}
			}
		}
		//TODO 数据校验
		
		if(context.hasError()){
			return ;
		}
		//执行Sql或JS
		if(urlConfig.getClazz()!=null){
			invoke(urlConfig.getClazz(), urlConfig.getMethod());
		}
		else if(urlConfig.getJs()!=null && !"".equals(urlConfig.getJs())){
			//执行JS
			JsHelper.execute(urlConfig.getJs());
		}
		super.invoke(chain);
	}
}
